import { Icon } from "@iconify-icon/react";
import {
  Button,
  Segmented,
  FloatButton,
  Select,
  Tooltip,
  message,
  Spin,
  Tag,
} from "antd";
import { useMainStore, changeFuncTab } from "@/store/mainStore";
import { useShallow } from "zustand/react/shallow";
import Ore from "./tsx/ore";
import styles from "./styles.module.less";
import Teleport from "./tsx/teleport";
import { useEffect, useRef, useState } from "react";
import {
  GetAllWindows,
  GetCharacterBaseAddress,
  HandleDrawWindowRectangle,
  ReadCharacterCoord,
  ReadCoordTableFile,
} from "@go/app/App";
import { RegisterHotkey } from "@go/app/HotkeyApp";
import throttle from "lodash.throttle";

const list = [
  {
    label: "瞬移",
    value: "teleport",
    icon: <Icon icon="solar:running-2-bold" />,
  },
  {
    label: "找矿",
    value: "ore",
    icon: <Icon icon="memory:pickaxe" />,
  },
  {
    label: "敬请期待...",
    value: "other",
    disabled: true,
  },
];

const High = () => {
  const highContentRef = useRef<HTMLDivElement>(null);
  const [tagTop, setTagTop] = useState(142);
  const { highInit, funcTab, isLogin, currentHwnd, hwndList, currentCoordObj } =
    useMainStore(
      useShallow((state) => ({
        funcTab: state.funcTab,
        isLogin: state.isLogin,
        currentHwnd: state.currentHwnd,
        hwndList: state.hwndList,
        highInit: state.highInit,
        currentCoordObj: state.currentCoordObj,
      }))
    );

  const getHwndList = async () => {
    const list1 = await GetAllWindows("", "七日世界");
    const list2 = await GetAllWindows("", "[#] 七日世界 [#]");
    const hwndList1 = (JSON.parse(list1) || [])
      .filter((item: any) => item.name)
      .map((item: any) => ({
        label: item.name,
        value: item.hwnd,
      }));
    const hwndList2 = (JSON.parse(list2) || [])
      .filter((item: any) => item.name)
      .map((item: any) => ({
        label: item.name,
        value: item.hwnd,
      }));
    const allList = [...hwndList1, ...hwndList2];
    console.log("hwndList", allList);
    // 如果在allList中找不到currentHwnd，则清空currentHwnd
    if (!allList.find((item) => item.value === currentHwnd)) {
      useMainStore.setState({ currentHwnd: undefined });
    }
    useMainStore.setState({ hwndList: allList });
  };

  useEffect(() => {
    getHwndList();
  }, []);

  useEffect(() => {
    async function init() {
      try {
        const coordJson = await ReadCoordTableFile();
        const coordList = JSON.parse(coordJson || "[]");
        useMainStore.setState({ coordList });
        if (coordList.length > 0) {
          message.success("坐标配置文件加载成功");
          // 注册热键
          coordList.forEach((item: any) => {
            if (item.hotkey) {
              RegisterHotkey(item.hotkey, item.id);
            }
          });
        }
      } catch (err) {
        message.error(`坐标配置文件加载失败: ${err}`);
      }
    }
    if (!highInit) {
      init();
      useMainStore.setState({ highInit: true });
    }
  }, [highInit]);

  useEffect(() => {
    let count = 0;
    let isAlert = false;
    const getCoordData = async () => {
      try {
        if (currentHwnd) {
          const coordJson = await ReadCharacterCoord(currentHwnd);
          const coord = JSON.parse(coordJson || "{}");
          if (Object.keys(coord).length === 0) {
            count++;
          } else {
            useMainStore.setState({ currentCoordObj: coord });
            count = 0;
            isAlert = false;
          }
          if (count > 5 && !isAlert) {
            message.warning("窗口句柄或基址失效,请点击右侧更新基址");
            isAlert = true;
          } else if (count > 60) {
            message.warning("窗口句柄或基址长时间失效,实时坐标已停止");
            useMainStore.setState({ currentHwnd: undefined });
          }
        } else {
          useMainStore.setState({ currentCoordObj: { x: 0, y: 0, z: 0 } });
        }
      } catch {}
    };
    const interval = setInterval(getCoordData, 1200);
    return () => clearInterval(interval);
  }, [currentHwnd]);

  useEffect(() => {
    const handleScroll = throttle(() => {
      const scrollTop = highContentRef.current?.scrollTop || 0;
      setTagTop(142 - scrollTop > 66 ? 142 - scrollTop : 66);
    }, 200);
    if (highContentRef.current) {
      highContentRef.current.addEventListener("scroll", handleScroll);
    }
    return () => {
      if (highContentRef.current) {
        highContentRef.current.removeEventListener("scroll", handleScroll);
      }
    };
  }, []);

  return (
    <div className={styles.highBox}>
      <div className={styles.highTop}>
        <Segmented
          options={list}
          value={funcTab}
          onChange={(tab) => {
            changeFuncTab(tab);
            if (tab === "ore") {
              message.warning("找矿功能暂未开发");
            }
          }}
        />
        <div style={{ display: "flex", alignItems: "center" }}>
          <span>游戏窗口：</span>
          <Select
            size="small"
            style={{ width: 150 }}
            // notFoundContent="暂无游戏窗口"
            allowClear
            value={currentHwnd}
            options={hwndList}
            onChange={(value: number) => {
              useMainStore.setState({ currentHwnd: value });
              if (value) {
                HandleDrawWindowRectangle(value, 255, 500, 20);
              }
            }}
            placeholder="请选择"
          />
          <Tooltip title="刷新" placement="left">
            <Button
              size="small"
              shape="circle"
              color="primary"
              variant="text"
              style={{ marginLeft: 5 }}
              icon={<Icon icon="material-symbols:refresh" />}
              onClick={getHwndList}
            />
          </Tooltip>
        </div>
      </div>
      <div className={styles.highContent} ref={highContentRef}>
        {currentHwnd && (
          <Tag
            bordered={false}
            color="processing"
            style={{
              position: "absolute",
              left: "49%",
              top: tagTop,
              zIndex: 10,
            }}
          >
            {`${currentCoordObj.x}, ${currentCoordObj.y}, ${currentCoordObj.z}`}
          </Tag>
        )}

        {funcTab === "teleport" && <Teleport />}
        {funcTab === "ore" && <Ore />}
        <FloatButton.BackTop
          target={() => highContentRef.current as HTMLElement}
          visibilityHeight={300}
          tooltip="回到顶部"
        />
      </div>
    </div>
  );
};

export default High;
